/*
 * @Description: 附近站点模块，如果该模块放入路由中，则需hasRouter设置为true，会在activated时刷新数据，deactivated关闭自动刷新计时器
 * @Author: yingying.fan
 * @Date: 2019-07-01 12:54:20
 * @Last Modified by: yingying.fan
 * @Last Modified time: 2019-07-01 13:02:08
 */
<template>
  <div>
    <net-error
      v-if="showType===1"
      @click.native="refreshData"
    ></net-error>
    <no-gps
      v-else-if="showType===2"
      :text="gpsErrorText"
      @click.native="clickNoGPS"
    ></no-gps>
    <template v-else-if="showType===3">
      <nearby-site
        v-for="(item,index) in list"
        :key="`nearbySite_${index}`"
        :stationInfo="item"
      >
      </nearby-site>
    </template>
  </div>
</template>

<script>
import NetError from './NetError'
import NoGPS from './NoGPS'
import NearbySiteItem from './NearbySiteItem'
import { getBusInfoWithDirection } from './api.js'
import { getCurrentPosition, goToGpsSettingPage, LOCATION_ERROR } from './LocationUtils.js'
const NET_ERROR = 1
const GPS_ERROR = 2
const HAS_DATA = 3

export default {
  components: {
    'net-error': NetError,
    'no-gps': NoGPS,
    'nearby-site': NearbySiteItem
  },
  props: {
    // 该组件是否被包裹在路由中，需要启用activated和deactivated生命周期
    hasRouter: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isActive: false, // 当前组件是否被激活
      gpsErrorText: '',
      repeatTime: window.prodInApp ? 15000 : 15000,
      busTimer: null,
      showType: 0,
      gpsErrorCode: '',
      errorHint: '',
      list: []
    }
  },
  mounted() {
    this.isActive = true
    this.addEvent()
    if (!this.hasRouter) {
      this.getBusInfo()
    }
  },
  destroyed() {
    this.clearBusTimer()
  },
  activated() {
    this.isActive = true
    this.getBusInfo()
  },
  deactivated() {
    this.isActive = false
    this.clearBusTimer()
  },
  methods: {
    addEvent() {
      document.addEventListener(
        'resume',
        () => {
          // 有数据时收到resume事件，自动刷新
          if (this.isActive && this.showType === HAS_DATA) {
            this.getBusInfo()
          }
        },
        false
      )
      document.addEventListener(
        'pause',
        () => {
          this.clearBusTimer()
        },
        false
      )
    },
    removeEvent() {

    },
    // 获取附近站点信息
    async getBusInfo() {
      console.log('~~~getBusInfo~~~' + new Date().getTime())
      this.clearBusTimer()
      try {
        let System = await this.$System
        System.getNetworkType(msg => {
          console.log('插件getNetworkType:' + msg)
          if (parseInt(msg) === 0) {
            // this.errorHint = '网络开小差了'
            this.setNetError()
          } else {
            this.getBusInfoByPosition()
          }
        }, () => {
          // 获取网络失败
          console.error('获取网络状态插件失败')
          this.getBusInfoByPosition()
        })
      } catch (error) {
        console.error('获取网络状态插件加载失败')
        this.getBusInfoByPosition()
      }
    },
    async getBusInfoByPosition() {
      try {
        let res = await getCurrentPosition(this)
        console.log('~~~getBusInfo协议~~~' + new Date().getTime())
        let siteList = await getBusInfoWithDirection(res.longitude, res.latitude)
        this.showType = HAS_DATA
        this.$EventBus.$emit('nearbyError', '')
        if (siteList.length > 0) {
          // 有数据
          this.list = siteList
        }
        this.busTimer = setTimeout(this.getBusInfo, this.repeatTime)
      } catch (error) {
        console.error(error.code + ':' + error.message)
        // 之前无数据的时候才提示错误
        if (error.code) {
          this.gpsErrorCode = error.code
          if (this.showType !== HAS_DATA) {
            this.showType = GPS_ERROR
            switch (error.code) {
              case LOCATION_ERROR.GPS_NOT_OPEN:
              case LOCATION_ERROR.GPS_SERVICE_ALWAYS_FORBID:
              case LOCATION_ERROR.GPS_SERVICE_ONCE_FORBID:
                // GPS未开启和GPS权限始终禁止，提示用户打开GPS
                // GPS权限单次禁止，获取定位，插件中弹框提示用户打开权限
                this.gpsErrorText = '获取定位失败，点击打开gps权限'
                break
              case LOCATION_ERROR.LOCATION_FAIL:
                // 获取定位失败时，获取定位，查询附近站点信息
                this.gpsErrorText = '获取定位失败'
                break
              case LOCATION_ERROR.PLUGIN_ERROR:
                this.gpsErrorText = '获取定位失败,插件加载失败啦~'
                break
              default:
                break
            }
          } else {
            this.$EventBus.$emit('nearbyError', '获取定位失败')
          }
        } else {
          // 除了定位以外的错误都提示网络失败
          this.setNetError()
        }
      }
    },
    setNetError() {
      if (this.showType !== HAS_DATA) {
        // 之前未获取到过数据才会展示网络错误
        // 网络错误缺省页需要用户点击刷新
        this.showType = NET_ERROR
      } else {
        // 只有黄色提示条的需要自动定时刷新
        this.$EventBus.$emit('nearbyError', '网络开小差了')
        this.busTimer = setTimeout(this.getBusInfo, this.repeatTime)
      }
    },
    // 清除定时器
    clearBusTimer() {
      if (this.busTimer) {
        clearTimeout(this.busTimer)
        this.busTimer = null
      }
    },
    // 点击没有gps的缺省页的跳转
    clickNoGPS() {
      switch (this.gpsErrorCode) {
        case LOCATION_ERROR.GPS_NOT_OPEN:
        case LOCATION_ERROR.GPS_SERVICE_ALWAYS_FORBID:
          // GPS未开启和GPS权限始终禁止，提示用户打开GPS
          goToGpsSettingPage(this)
          break
        case LOCATION_ERROR.GPS_SERVICE_ONCE_FORBID:
        case LOCATION_ERROR.LOCATION_FAIL:
          // GPS权限单次禁止和获取定位失败，获取定位，插件中弹框提示用户打开权限
          this.getBusInfo()
          break
      }
    },
    // 网络失败时点击刷新
    refreshData() {
      this.getBusInfo()
    }
  }
}
</script>

<style scoped>
.not-network-page {
  padding: 0 !important;
}
</style>
